<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace plugins\blog\api\controller;

use think\exception\ValidateException;
use app\api\BaseController;
use plugins\blog\api\validate\UserNotice as Validate;
use plugins\blog\api\model\Blog;
use plugins\blog\api\model\BlogNotice;
/**
 * 我的通知
 */
class UserNotice extends BaseController
{
    /**
     * 用户权鉴
     */
    public $middleware = [\app\api\middleware\AuthCheck::class];
    
    /**
     * 通知
     */
    public function index() 
    {
        if ($this->request->isPost()) {
            try {
                $input = input('post.');
                validate(Validate::class)->scene('index')->check($input);
            } catch ( ValidateException $e ) {
                return json(['status' => 'error', 'message' => $e->getError()]);
            }
            $where[] = ['type', '=', $input['type']];
            $where[] = ['to_id', '=', $this->request->userId];
            $count   = BlogNotice::where($where)->count();
            $data    = BlogNotice::where($where)->with(['user','blog'])->order('create_time', 'desc')->page($input['page'], 10)->select();
            foreach ($data as $val) {
                BlogNotice::where('id', $val->id)->update(['unread' => 1]);
            }
            return json(['status' => 'success', 'message' => '获取成功', 'data' => $data, 'count' => $count]);
        }
    }
    
    /**
     * 保存新建的资源
     */
    public function save()
    {
        if ($this->request->isPost()) {
            try {
                $input = input('post.');
                validate(Validate::class)->scene('save')->check($input);
            } catch ( ValidateException $e ) {
                return json(['status' => 'error', 'message' => $e->getError()]);
            }
            $blog  = Blog::where('id',$input['id'])->value();
            $data  = BlogNotice::create([
                'to_id'       => $input['user_id'],
                'blog_id'     => $blog->id,
                'blog_cover'  => $blog->cover,
                'blog_title'  => $blog->title,
                'notice'      => $input['notice'],
                'type'        => $input['type'],
                'user_id'     => $this->request->userId,
                'unread'      => 0,
                'create_time' => date('Y-m-d H:i:s'),
            ]);
            return json(['status' => 'success', 'message' => '记录成功', 'data' => $data]);
        }
    }
}